$(function(){
    
    //初始化左侧组织架构树
    orgTree.init();
    
	sys.selectpicker({
		id:'status',  //select的id
		url: rootPath + "/dict/listKeyMapEntites",  //请求数据的远程地址
		param: {keyType : 'status'}, //过滤参数
		//defaultValue:{},
		valueField: 'keyValue',
		textField: 'keyIntro',
		width: '200px'});
		//定义列
	var columns = [ 
					{ field: 'no', title: '序号', 
						valign : 'middle',
						align: 'left', 
						formatter: function (value, row, index) {
							return index+1;
						}
					},
					{ field: 'userCode', title: '工号',valign : 'middle', align: 'center' },
					{ field: 'userName', title: '用户名称',valign : 'middle', align: 'center' },
					{ field: 'orgName', title: '部门',valign : 'middle', align: 'center' },
					{ field: 'roleName', title: '角色', valign : 'middle', align: 'center' },
					{ field: 'mobile', title: '电话',valign : 'middle', align: 'center' },
					{ field: 'userType', title: '用户类型',valign : 'middle', align: 'center' ,
						formatter: function (value, row, index) {
							if (value == "1"){
					    		return "<span >管理员</span>";
					    	}else if (value == "2"){
					    		return "<span >业务员</span>";
					    	}else if (value == "3"){
					    		return "<span >经销商</span>";
					    	}
						}
					},
					{ field: 'status', title: '状态',valign : 'middle', align: 'center' ,
						formatter: function (value, row, index) {
							if (value == "1"){
					    		return "<span class='label label-success'>启用</span>";
					    	}else if (value == "0"){
					    		return "<span class='label label-danger'>停用</span>";
					    	}
						}
					},
					{ field: '#', title: '操作',valign : 'middle', align: 'center' ,
						formatter: function (value, row, index) {
							if(row.status == '1'){
								return "<div style='padding-top:5px;'><a class='btn btn-danger btn-xs' href='javaScript:void(0);'onclick='updateStatus("+row.id+","+row.status+")'>停用</a>"
								+"<a class='btn btn-info btn-xs' href='javaScript:void(0);'onclick='updateUser("+row.id+")'>编辑</a>"
								+"<a class='btn btn-warning btn-xs' href='javaScript:void(0);'onclick='assginUserRole("+row.id+")'>分配角色</a>"
								+"<a class='btn btn-primary btn-xs' href='javaScript:void(0);'onclick='resetPwd("+row.id+")'>重置密码</a></div>";
						}else{
							
							return "<div style='padding-top:5px;'><a class='btn btn-success btn-xs' href='javaScript:void(0);'onclick='updateStatus("+row.id+","+row.status+")'>启用</a>"
							+"<a class='btn btn-info btn-xs' href='javaScript:void(0);'onclick='updateUser("+row.id+")'>编辑</a>"
							+"<a class='btn btn-warning btn-xs' href='javaScript:void(0);'onclick='assginUserRole("+row.id+")'>分配角色</a>"
							+"<a class='btn btn-primary btn-xs' href='javaScript:void(0);'onclick='resetPwd("+row.id+")'>重置密码</a></div>";
						}
					}
					},
				];
	//定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) { 
		var userName = $("#userName").val();
		var userCode = $("#userCode").val();
		var mobile = $("#mobile").val();
		var status = $("#status").val();
		var orgId = $("#orgId").val();
		return {
			rows: params.limit, //页面大小 
  		 	page: params.pageNumber, //页码 
  		 	status: status,
  		 	userName: userName,
  		 	userCode: userCode,
  		 	mobile: mobile,
  		 	orgId: orgId
	  	}; 
	};
	var url = rootPath+"/user/getUserList"; //请求json数据的服务器地址
	sys.initTable('myTable', {url: url, 
		queryParams:queryParams, 
		columns: columns,  
		striped: true,
		clickToSelect: true
	});
	
	$('#btnClear').on('click', function(){
		$("#position-form").find("input[type='text']").val("");
		$("#position-form").find("#status").val("");
	});
	$('#btnQuery').on('click', function(){
		sys.reloadTable('myTable');
	});
	$('#btnClear').on('click', function(){
		$("#position-form").find("input[type='text']").val("");
	});
	
	$('#btnAdd').on('click', function(){
		window.location.href=rootPath+"/user/toAddUser";
	});
	
})

//编辑
function updateUser(id){
	window.location.href=rootPath+"/user/toUpdateUser?id="+id;
}

//分配角色
function assginUserRole(id){
	window.location.href=rootPath+"/user/toAssginUserRole?id="+id;
}

//重置密码
function resetPwd(id){
	showConfirm("确定要重置密码吗？", function(){
		$.ajax({
			url : rootPath+"/user/resetUserPwd",
			type : "post",
			async : true,
			dataType : 'json',
			data:{id:id},
			success : function(json) {
				if(json.resultCode == '1'){
					showSuccess(json.resultMsg);
				}else{
					showSuccess(json.resultMsg);
				}
			}
		});
	})
	
}
function updateStatus(id,status){
		var msg="确定要停用该角色吗？"
		var url =rootPath +"/user/disableUser";
			if(status == '0'){
				msg="确定要启用该角色吗？"
				url=rootPath +"/user/enableUser";
			}
			showConfirm(msg, function(){
				$.ajax({
					url : url,
					type : "post",
					async : true,
					dataType : 'json',
					data:{id:id},
					success : function(json) {
						if (json.resultCode == "1") {
							showSuccess(json.resultMsg,sys.reloadTable('myTable'));
						}else{
							showErr(json.resultMsg,sys.reloadTable('myTable'));
						}
					}
				});
			})
}


var orgTree = (function(){
    //url
    var URLs = {
            listOrg : rootPath + "/org/listOrg"
        };
    //树ID
    var treeName = 'orgTree'; 
    //zTree对象
    var tree = $("#" + treeName);
    //zTree设置
    var setting = {
            view: {
                //addHoverDom: addHoverDom,
                //removeHoverDom: removeHoverDom
            },
            data : {
                simpleData : {
                    enable  : true,
                    idKey   : 'id',
                    pIdKey  : 'parentId',
                    rootPId : "0"
                }
            },
            callback : {
                onClick : onClick
            }
    };
    
    /**
     * 点击菜单击事件
     * @param e
     * @param treeId 树节点ID
     * @param treeNode 树节点对象
     */
    function onClick(e, treeId, treeNode) {
        $("#orgId").val(treeNode.id);
        // 判断组织信息div是否处于隐藏状态
        var isHidden = $("#orgInfo").is(":hidden");
        if (isHidden) {
            $("#orgInfo").show();
        }
        sys.reloadTable('myTable');
    }
    
    return {
        
        /**
         * 创建组织树
         * @returns 返回初始化后的zTree对象
         */
        init: function(){
            var nodes = [];
            /**
             * 查询所有组织
             */
            $.ajax({
                url : URLs.listOrg,
                async : false,
                dataType : 'json',
                type : 'post',
                success : function(result) {
                    if (result.treeList != null) {
                        $.each(result.treeList, function(index, row) {
                            nodes.push({
                                id : row.id,
                                parentId : row.parentId,
                                name : row.orgName,
                                orgCode : row.orgCode,
                                orgStatus : row.status
                            });
                        });
                    }
                }
            });
            var treeObj = $.fn.zTree.init(tree, setting, nodes);
            //全部展开
            treeObj.expandAll(false); 
            return treeObj;
        }
    };
})();